// pages/oneself/redact/redact.js
const myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(19[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
const myemail = /^[0-9a-zA-Z]{3,20}\@[0-9a-zA-Z]{1,5}\.[a-z]{1,5}$/;
const app = getApp()
const connector = require('../../../utils/connector.js');
const qiniuUploader = require('../../../utils/qiniuUploader.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    fileJudge: false,//是否正在上传
    progressNum: 0,//上传进度
    fileArr: [],//上传的图片集合

    array: [//驾校
  
      ],
    schoolIndex: 0,//驾校选择下标

    sex: '1',
    types: [//所有班型
      { name: 'A1', value: 'A1大型客车' },
      { name: 'A2', value: 'A2牵引车' },
      { name: 'A3', value: 'A3城市公交车' },
      { name: 'B1', value: 'B1中型客车' },
      { name: 'B2', value: 'B2大型货车' },
      { name: 'C1', value: 'C1手动挡' },
      { name: 'C2', value: 'C2自动挡' },
      { name: 'D、E', value: 'D、E摩托车' },

    ],
    typesStr: '请选择班型',
    typesView: false,//班型选择框弹出/关闭
    typesVal: [],//班型选择结果
  },
  //图片上传
  chatI: function () {
    var that = this;
    // console.log(connector.connector().filePath)
    let obj = {

    }
    connector.getFunc(app.conUser + connector.connector().filePath, obj, "post", app.tokens, function (res) {
      // console.log(res.data[0].upToken)
      chatI(that, res.data[0].upToken, res.data[0].domain, "head/");

    }, function (res) {
      console.log(res)

    })
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      schoolIndex: e.detail.value
    })
  },
  //打开/关闭班型选择弹框
  typesView(e) {
    this.setData({
      typesView: !this.data.typesView
    })
  },
  // //获取班型

  // bxxzBc(e) {
  //   let that = this
  //   // console.log(e.detail.value)
  //   let arr = e.detail.value.types
  //   let str = ''
  //   console.log(arr)
  //   for (let i = 0; i < arr.length; i++) {
  //     if (i == 0) {
  //       str += arr[i]
  //     } else {
  //       str = str + "," + arr[i]
  //     }
  //   }
  //   console.log(str)
  //   that.setData({
  //     typesVal: arr,
  //     typesView: false,
  //     typesStr: str
  //   })

  // },
  //表单提交
  formSubmit: function (e) {
    var that = this
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let list = e.detail.value
    // console.log(list.name)
    if (list.name == '') {
      wx.showToast({
        title: "请输入姓名",
        icon: 'none',
        duration: 1000
      })
      return false
    }

    // !(/^[0-9a-zA-Z]{3,20}\@[0-9a-zA-Z]{1,5}\.[a-z]{1,5}$/.test(str))
    // if (list.age == '') {
    //   wx.showToast({
    //     title: "请输入年龄",
    //     icon: 'none',
    //     duration: 1000
    //   })
    //   return false
    // }
    if (list.phone == '') {
      wx.showToast({
        title: "请输入联系电话",
        icon: 'none',
        duration: 1000
      })

      return false
    } else {
      if (list.phone.length < 11 || !myreg.test(list.phone)) {
        wx.showToast({
          title: "联系电话输入有误",
          icon: 'none',
          duration: 1000
        })
        return false
      }
    }
    // if (that.data.typesVal.length < 1) {
    //   wx.showToast({
    //     title: "请选择班型",
    //     icon: 'none',
    //     duration: 1000
    //   })
    //   return false
    // }
    if (that.data.schoolIndex == 0) {
      wx.showToast({
        title: "请选择驾校",
        icon: 'none',
        duration: 1000
      })
      return false
    }
    if (that.data.fileArr.length < 1){
      wx.showToast({
        title: "上传戴工作牌的上半身照片",
        icon: 'none',
        duration: 1000
      })
      return false
    }


    list.desc = ""
    list.school_id = that.data.array[that.data.schoolIndex].school_id
    list.picture = that.data.fileArr[0].file.imageURL
    // if (list.email != '') {
    //   if (!(myemail.test(list.email))) {
    //     wx.showToast({
    //       title: "邮箱输入错误",
    //       icon: 'none',
    //       duration: 1000
    //     })
    //     return false
    //   }
    // }
    console.log(list)
    coachAuth(that, list)
    // wx.showModal({
    //   title: '提示',
    //   content: '教练认证审核提交成功，驾校将在1-3个工作日内审核，如长时间未审核请联系驾校管理人员',
    //   success: function (res) {
    //     if (res.confirm) {
    //       // console.log('用户点击确定')
    //     } else if (res.cancel) {
    //       // console.log('用户点击取消')
    //     }
    //   }
    // })
    // wxUpd(that, e.detail.value)

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    schoolList(this)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
    // let user = wx.getStorageSync("myUser")
    // console.log(user)
    // let name = user.name,
    //   phone = user.phone,
    //   sex = user.sex,
    //   email = user.email;
    // if (name == '' || !name) name = ""

    // if (phone == '' || !phone) phone = ""

    // // if (sex == 1) sex = "男"
    // // else if (sex == 2) sex = "女"
    // // else sex = ""

    // if (email == '' || !email) email = ""
    // this.setData({
    //   phone: phone,
    //   name: name,
    //   sex: sex,
    //   email: email
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
  onPullDownRefresh: function () {
    var that = this
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新

  },
})


//获取驾校名
function schoolList(that) {
  connector.getFuncSchool(function(res){
    console.log(res)
    if (res.statusCode == 200){
      that.setData({
        array: res.data
      })
    }else{
      wx.showToast({
        title: res.errMsg,
        icon: 'none',
        duration: 1000
      })
    }
  },function(res){
    console.log(res)
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}

// 初始化七牛相关参数
function initQiniu(tok, domain) {
  var options = {
    region: 'SCN', // 华南区
    // uptokenURL: 'https://minitest.17jxyx.com/api/v1/token/file/goods',
    uptoken: tok,
    uploadURL: 'https://up-z2.qbox.me/',
    domain: domain,
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}
//单图片上传 token:七牛上传token;types:上传文件前缀
function chatI(that, token, domain, types) {
  initQiniu(token, domain);
  // 微信 API 选文件
  wx.chooseImage({
    count: 1,
    success: function (res) {
      if (that.data.fileArr.length > 0) {
        deleteFile(that.data.fileArr[0].file.key)
      }
      let filePath = res.tempFilePaths[0];
      let obj = {
        tempFilePaths: filePath
      }
      let arr = []
      arr.push(obj)
      that.setData({
        tempFilePaths: filePath,
        fileJudge: true,
        fileArr: arr
      })
      let houzhui = filePath.lastIndexOf(".")
      let sss = filePath.slice(houzhui)
      let keys = filePath.slice(houzhui - 5, houzhui)
      let timestamp = (new Date()).getTime();
      let fileName = types + timestamp + keys + sss

      // 交给七牛上传
      qiniuUploader.upload(filePath, fileName, (ser) => {
        console.log(ser)
        let fileArr = that.data.fileArr
        fileArr[0].file = ser
        that.setData({
          fileArr: fileArr
        })
        console.log(fileArr)
      }, (error) => {
        console.error('error: ' + JSON.stringify(error));
      },
        null,// 可以使用上述参数，或者使用 null 作为参数占位符
        (progress) => {
          that.setData({
            progressNum: progress.progress
          })
          if (progress.progress == 100) {
            that.setData({
              fileJudge: false
            })
          }
        }, cancelTask => that.setData({ cancelTask })
      );
    }
  })
}
//删除七牛云图片
function deleteFile(fileKey) {
  console.log(fileKey)
  let obj = {
    fileName: fileKey
  }
  connector.getFunc(app.conUser + connector.connector().fileDelete, obj, "post", app.tokens, function (res) {
    // console.log(res.data[0].upToken)
    console.log(res)

  }, function (res) {
    console.log(res)
  })
}

//提交审核
function coachAuth(that,obj) {
  console.log(obj)
  connector.getFunc(connector.connector().coachAuth, obj, "post", app.tokens, function (res) {
    // console.log(res.data[0].upToken)
    console.log(res)
    if (res.statusCode == 200){
      wx.showModal({
        title: '提示',
        content: '教练认证审核提交成功，驾校将在1-3个工作日内审核，如长时间未审核请联系驾校管理人员',
        success: function (res) {
          if (res.confirm) {
            // console.log('用户点击确定')
            wx.navigateBack({
              delta: 1,
            })
          } else if (res.cancel) {
            // console.log('用户点击取消')
            wx.navigateBack({
              delta: 1,
            })
          }
        }
      })
    }else{
      wx.showToast({
        title: res.errMsg,
        icon: 'none',
        duration: 1000
      })
    }

  }, function (res) {
    console.log(res)
  })
}